ES Module
Piscina supports ES modules (ESM) out of the box. This example demonstrates how to use Piscina with ES modules in both the main script and the worker file.
- Javascript
- Typescript
index.mjs
import { Piscina } from "piscina";
const piscina = new Piscina({
filename: new URL("./worker.mjs", import.meta.url).href,
});
(async () => {
const result = await piscina.run({ a: 4, b: 6 });
console.log(result);
})(); // Prints 10
index.ts
import Piscina from "piscina";
import { resolve } from "path";
import { filename } from "./worker";
const piscina = new Piscina({
filename: resolve(__dirname, "./workerWrapper.js"),
workerData: { fullpath: filename },
});
(async () => {
const result = await piscina.run({ a: 4, b: 6 });
console.log(result);
})();
The worker file is a simple ES module that exports a default function:
- Javascript
- Typescript
worker.mjs
export default ({ a, b }) => {
return a + b;
};
worker.ts
interface Input {
a: number;
b: number;
}
export default ({ a, b }: Input): number => {
return a + b;
};
You can also check out this example on github.